package com.netease.controller;

import com.huaban.analysis.jieba.JiebaSegmenter;

import com.netease.service.RootInfoService;
import com.netease.bo.RootInfoBO;
import com.netease.entity.Word;
import com.netease.service.StandFieldService;
import com.netease.service.impl.StandFieldServiceImpl;
import com.netease.service.impl.RootInfoServiceImpl;
import com.netease.pojo.RootInfo;
import com.netease.utils.CsvUtils;
import com.netease.utils.DateUtil;
import com.netease.utils.JsonResult;
import com.netease.utils.PagedGridResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @projectName: modeling-dev
 * @package: com.netease.controller
 * @className: WordSegmentController
 * @author: aochong
 * @description: 分词Controller
 * @date: 2023/4/3 10:46
 * @version: 1.0
 */
@Api(value = "词根接口", tags = {"标准词根相关接口"})
@RequestMapping("root")
@RestController
public class RootInfoController {

    private JiebaSegmenter segmenter = new JiebaSegmenter();
    private static final String PATH = "modeling-service/src/main/resources/dicts/user.dict";

    public static final Integer COMMON_PAGE_SIZE = 10;

    @Autowired
    private RootInfoService rootInfoService = new RootInfoServiceImpl();

    @Autowired
    private StandFieldService standFieldService = new StandFieldServiceImpl();

    @ApiOperation(value = "词根分页查询", notes = "词根分页查询", httpMethod = "GET")
    @GetMapping("/list")
    public JsonResult list(
            @ApiParam(name = "page", value = "查询下一页的第几页", required = false)
            @RequestParam Integer page,
            @ApiParam(name = "pageSize", value = "分页的每一页显示的条数", required = false)
            @RequestParam Integer pageSize
    ) {

        if (page == null) {
            page = 1;
        }

        if (pageSize == null) {
            pageSize = COMMON_PAGE_SIZE;
        }

        PagedGridResult grid = rootInfoService.queryPagedRoots(page, pageSize);

        return JsonResult.ok(grid);
    }

    @ApiOperation(value = "修改词根", notes = "修改词根", httpMethod = "POST")
    @PostMapping("/update")
    public JsonResult update(@RequestBody RootInfoBO rootInfoBO) {
        Word word = new Word();
        word.setName(rootInfoBO.getRootChnsNm());
        word.setEngAbbreviation(rootInfoBO.getRootNm());
        word.setEngName(rootInfoBO.getTranslt());
        word.setBsinssPlate(rootInfoBO.getBsinssPlate());

        //判断词根中文名称||词根英文名称||业务板块必须不能为空
        if (StringUtils.isBlank(word.getName()) ||
                StringUtils.isBlank(word.getEngName()) ) {
            return JsonResult.errorMsg("词根中文名称||词根标准英文必须不为空！！！");
        }

        // 1. 查询词根是否存在
        boolean isExist = rootInfoService.queryRootIsExist(word);

        if (!isExist) {
            return JsonResult.errorMsg("该词根在数据库中不存在！！！");
        }else{
            RootInfo rootInfo = rootInfoService.queryRoot(word);
            if (StringUtils.isNotBlank(word.getName())){
                rootInfo.setRootChnsNm(word.getName());
            }
            if (StringUtils.isNotBlank(word.getEngName())){
                rootInfo.setTranslt(word.getEngName());
            }
            if (StringUtils.isNotBlank(word.getEngAbbreviation())){
                rootInfo.setRootNm(word.getEngAbbreviation());
            }
            if (StringUtils.isNotBlank(word.getBsinssPlate())) {
                rootInfo.setBsinssPlate(word.getBsinssPlate());
            }
            rootInfo.setIsReview("是");
            rootInfo.setUpdateTime(DateUtil.dateToString(new Date()));
            //TODO 更新词根
            rootInfoService.updateRoot(rootInfo);
        }

        return JsonResult.ok();
    }

    @ApiOperation(value = "查询词根", notes = "查询词根，用法：单个词根直接输入词根中文名称，多个词根之间用空格分隔，例如：条件 查询", httpMethod = "GET")
    @GetMapping("/select")
    public String select(@RequestParam String rootName) {

        //判断词根中文名称||词根英文名称||业务板块必须不能为空
        if (StringUtils.isBlank(rootName)) {
            JsonResult.errorMsg("请输入要查询的词根中文名称，多个词根请使用空格符进行分割，如：单词 条件！");
        }

        String[] rootNames = rootName.split(" ");
        StringBuilder sb = new StringBuilder();
        for (String name : rootNames) {
            Word word = new Word();
            word.setName(name);

            // 1. 查询词根是否存在
            boolean isExist = rootInfoService.queryRootIsExist(word);

            if (!isExist) {
                sb.append(name)
                        .append(",")
                        .append("词根不存在，请使用标准字段生成接口进行生成！")
                        .append(",")
                        .append(",")
                        .append("<BR />");
            }else {
                RootInfo rootInfo = rootInfoService.queryRoot(word);
                sb.append(rootInfo.getRootChnsNm())
                        .append(",")
                        .append(rootInfo.getTranslt())
                        .append(",")
                        .append(rootInfo.getWordFrequency())
                        .append(",")
                        .append(rootInfo.getRootNm())
                        .append("<BR />");
            }
        }

        return sb.toString();
    }

    @ApiOperation(value = "词根批量更新&新增", notes = "词根批量更新&新增", httpMethod = "POST")
    @PostMapping("/batchUpdata")
    public JsonResult generateByFile(@RequestParam("csvFile") MultipartFile file) {

        //读取CSV文件内容
        List<String> lines = CsvUtils.readCsvFile(file);

        if(lines.size()==0 && lines.isEmpty()){
            //文件内容为空
            return JsonResult.errorMsg(null);
        }

        ArrayList<RootInfo> rootInfos = new ArrayList<>();
        RootInfo rootInfo = null;
        try {
            for (int i = 0; i < lines.size(); i++) {
                String[] fields = lines.get(i).split(",");
                rootInfo = new RootInfo();
                rootInfo.setRootChnsNm(fields[0]);
                if (StringUtils.isNotBlank(fields[1])) {
                    rootInfo.setTranslt(fields[1]);
                } else {
                    rootInfo.setTranslt("");
                }
                if (StringUtils.isNotBlank(fields[2])) {
                    rootInfo.setWordFrequency(Integer.parseInt(fields[2]));
                }else{
                    rootInfo.setWordFrequency(1);
                }
                rootInfo.setRootNm(fields[3]);
                if (StringUtils.isNotBlank(fields[4])) {
                    rootInfo.setIsReview(fields[4]);
                }else{
                    rootInfo.setIsReview("是");
                }
                rootInfos.add(rootInfo);
            }

            rootInfoService.batchUpdate(rootInfos);
        }catch (Exception e){
            System.out.println(rootInfo);
            e.printStackTrace();
        }

        return JsonResult.ok("已完成！");
    }

}
